#!/bin/bash 
# check_install.sh checks to see if it is possible to take down all the virtual machine(s)
# Copyright (C) 2008 Rene Geers (rene.geers@gmail.com) and Bjoern Remseth (la3lma@gmail.com)
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

IFS=$'\x0A'$'\x0D'
IPDB=/data/etc/VMS
#DEBUG=1
if [ $DEBUG ];then
   echo "Debugmode"
else
   echo "This script will take all you virtual machines down!! Press Ctrl-C now if you did not intent this"
   echo "Realmode"
   sleep 4
fi

VMS=`vmware-cmd -l`
for VM in $VMS; do
   VMDIR=`echo $VM|cut -d"/" -f1-4`
   OS=`grep OS "$VM"|cut -d " " -f 3|sed s/\"//g`
   if [ ${OS:0:3} = "win" ]; then
     OS=WIN
   else
     OS=LIN
   fi
   #echo $OS $VM

   IP=`grep $VM $IPDB|cut -d" " -f 1`

   if [ `vmware-cmd $VM getstate` = "getstate() = on" ]; then
      if [ $OS = "LIN" ]; then
	 if [ $IP = "NAT" ]; then
	    echo "Warning: This VM cannot be stopped before the IP is registered in $IPDB!"
	    echo "Warning: Your backup now contains a dirty backup of this machine"
         else
            if [ $DEBUG ]; then
               echo ssh $IP sudo halt
            else
               echo ssh $IP sudo halt
               ssh $IP sudo halt
            fi
         fi
      else
         if [ -n $DEBUG ]; then
            echo vmware-cmd "$VM" stop
         else
            sudo vmware-cmd "$VM" stop
         fi
      fi

      #Bring the VM down controlled
      A=0
      while [ "`vmware-cmd $VM getstate`" = "getstate() = on" ]; do
	echo "Sleeping..."
        A=$(($A+1))
	if [ $A = "10" ]; then
           echo "Killing virtuall machine"
           if [ ! $DEBUG ]; then
	      sudo vmware-cmd "$VM" stop hard
           fi
	   break
	fi
	sleep 4
      done

   fi

done
